import os

from django import forms
from django.conf import settings
from django.contrib import admin
from django.db.models import TextField
from django.forms.models import ModelFormMetaclass
from django.utils.text import capfirst
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _

import widgets

def modify_class_attrs(parent, modifier):
    class ChildBase(parent.__metaclass__):
        def __new__(cls, name, bases, attrs):
            return super(ChildBase, cls).__new__(cls, name, bases, modifier(attrs))
    class Child(parent):
        __metaclass__ = ChildBase
    return Child


def create_advanced_admin_form(form_model, mix=None, visual_editor=()):
    class FormBase(ModelFormMetaclass):
        def __new__(cls, name, bases, attrs):
            for field in form_model._meta.fields:
                fclass = field.__class__.__name__
                fieldattrs = {
                    'label': capfirst(field.verbose_name),
                    'required': not field.blank,
                }

                if fclass == 'ImageField':
                    fieldattrs['widget'] = widgets.AdminImageWidget()
                    attrs[field.name] = forms.ImageField(**fieldattrs)
                elif fclass == 'FileField':
                    fieldattrs['widget'] = widgets.AdminFileWidget()
                    attrs[field.name] = forms.FileField(**fieldattrs)
                elif field.name in visual_editor:
                    fieldattrs['widget'] = widgets.VisualEditorWidget()
                    attrs[field.name] = forms.CharField(**fieldattrs)

                if mix:
                    attrs.update(mix.__dict__)

            return super(FormBase, cls).__new__(cls, name, bases, attrs)

    class Form(forms.ModelForm):
        __metaclass__ = FormBase
        class Meta:
            model = form_model

    return Form


def create_preview_field(description, image_field_name, descr_field_name=None,
    max_size=None
):
    from django.utils.encoding import smart_unicode, smart_str, force_unicode
    def field(self):
        image_field = getattr(self, image_field_name)
        if not image_field:
            return ''
        descr = descr_field_name and getattr(self, descr_field_name) or ''
        if max_size and (image_field.width, image_field.height) > max_size:
            result = u'<a href="%s">%s: %dx%d</a>' % (image_field.url,
                _('big image'), image_field.width, image_field.height)
        else:
            result = u'<img src="%s" width="%d" height="%d" alt="%s"/>' % (
                image_field.url, image_field.width, image_field.height, descr)
        return mark_safe(result)

    field.short_description = description
    field.allow_tags = True
    return field

def create_link_field(description, file_field_name, descr_field_name=None):
    def field(self):
        file_field = getattr(self, file_field_name)
        return file_field.url
    field.short_description = description
    return field

def unix_path(str):
    return unicode(str).replace('\\', '/')


